package com.hcmus.arLocation;

import global.global;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.GeoPoint;
import com.hcmus.armobile.R;


import config.config;

//import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources.NotFoundException;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ArLocation extends AugmentedActivity {
	private static final String TAG = "MainActivity";
	private static final String locale = "en";
	private static final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(
			1);
	private static final ThreadPoolExecutor exeService = new ThreadPoolExecutor(
			1, 1, 20, TimeUnit.SECONDS, queue);
	private static final Map<String, NetworkDataSource> sources = new ConcurrentHashMap<String, NetworkDataSource>();
	private MapView map = null;
	private long lastTouchTimeDown = -1;
	private long lastTouchTimeUp = -1;
	private static Context ct = null;
	private int counterRequestServer = 0;
	
	/*push notification**/
	 
	 // static final String TAG = "AndroidHive GCM";

   
	AsyncTask<Void, Void, Void> mRegisterTask;
	
	 /* end push notfiction*/

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
					
		LocalDataSource localData = new LocalDataSource(this.getResources());
		ARData.addMarkers(localData.getMarkers());
		ct = this;
		NetworkDataSource DentifierDB = new DentifierDataSource(
				this.getResources(), this);
		sources.put("DentifierDaTa", DentifierDB);
		// NetworkDataSource wikipedia = new
		// WikipediaDataSource(this.getResources());
		// sources.put("wiki",wikipedia);
	}

	@Override
	public void onStart() {
		super.onStart();
		// lay gps location user current standing
		Location last = ARData.getCurrentLocation();
		global.lat = String.valueOf(last.getLatitude());
		global.lng = String.valueOf(last.getLongitude());
		updateData(last.getLatitude(), last.getLongitude(), last.getAltitude());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_ar, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.v(TAG, "onOptionsItemSelected() item=" + item);
		switch (item.getItemId()) {
		case R.id.showRadar:
			showRadar = !showRadar;
			item.setTitle(((showRadar) ? "Hide" : "Show") + " Radar");
			break;
		case R.id.showZoomBar:
			showZoomBar = !showZoomBar;
			item.setTitle(((showZoomBar) ? "Hide" : "Show") + " Zoom Bar");
			zoomLayout.setVisibility((showZoomBar) ? LinearLayout.VISIBLE
					: LinearLayout.GONE);
			break;
		case R.id.exit:
			finish();
			break;
		case R.id.showmap:
			// Toast.makeText(this, ARData.getMarkers().size(), 30).show();
			Intent inMap = new Intent(ArLocation.this, GeoMappingMarker.class);
			this.startActivity(inMap);
			break;
		case R.id.showCounterRequest:
			Toast.makeText(this,"===== counter request : " + this.counterRequestServer,10).show();
		}
		return true;
	}

	@Override
	public void onLocationChanged(Location location) {
		super.onLocationChanged(location);

		//
		global.lat = String.valueOf(location.getLatitude());
		global.lng = String.valueOf(location.getLongitude());
		//
		updateData(location.getLatitude(), location.getLongitude(),
				location.getAltitude());
	}

	@Override
	protected void markerTouched(Marker marker) {
		// Function Click Marker
		// Toast t = Toast.makeText(getApplicationContext(), marker.getName(),
		// Toast.LENGTH_SHORT);
		// t.setGravity(Gravity.CENTER, 0, 0);
		// t.show();
		Intent in = new Intent(ArLocation.this, DetailLocation.class);
		in.putExtra("location_name_to", marker.getName());
		in.putExtra("location_address_to", marker.getAddressShopping());
		in.putExtra("location_promotion_to", marker.getpromotionShopping());
		in.putExtra("location_Location_type_to", marker.getIDChainShopping());
		in.putExtra("location_ChainShopName_to", marker.getChainShoppingName());
		in.putExtra("location_lon_to",
				String.valueOf(marker.physicalLocation.getLongitude()));
		in.putExtra("location_lat_to",
				String.valueOf(marker.physicalLocation.getLatitude()));
		this.startActivity(in);
	}

	@Override
	protected void updateDataOnZoom() {
		super.updateDataOnZoom();
		Location last = ARData.getCurrentLocation();
		updateData(last.getLatitude(), last.getLongitude(), last.getAltitude());
	}

	private void updateData(final double lat, final double lon, final double alt) {
		try {
			exeService.execute(new Runnable() {

				public void run() {
					for (NetworkDataSource source : sources.values())
						download(source, lat, lon, alt);
				}
			});
		} catch (RejectedExecutionException rej) {
			Log.w(TAG, "Not running new download Runnable, queue is full.");
		} catch (Exception e) {
			Log.e(TAG, "Exception running download Runnable.", e);
		}
	}

	private boolean download(NetworkDataSource source, double lat,
			double lon, double alt) {
		if (source == null)
			return false;

		// String url = null;
		// try {
		// url = source.createRequestURL(lat, lon, alt, ARData.getRadius(),
		// locale);
		// } catch (NullPointerException e) {
		// return false;
		// }
		List<Marker> markers = null;

		if (config.post2Server == false) {
			try {
				JSONObject objData = DentifierDataSource
						.LoadDataSource("SELECT * FROM LocationInformation li LEFT JOIN LocationType lt ON(li.IDLocationShoppingType = lt.IDLocationType) ORDER BY li.ID ASC");
				markers = source.parse(objData);
			} catch (NullPointerException e) {
				return false;
			}

		} else {
			try {
				
				// //
				// if(lat != 0 && lon != 0){
				// global.lat = String.valueOf(lat);
				// global.lng = String.valueOf(lon);
				// //
				// }

				// Location currLocation = ARData.getCurrentLocation();
				//Log.e(TAG, "======================= call server: " + global.lat
					//	+ " ==== " + global.lng + "---" + global.distance);
				
				JSONObject objData = DentifierDataSource
						.LoadDataSourcePostNew(global.lat, global.lng,
								String.valueOf(global.distance));// ARData.getRadius()
				this.counterRequestServer += 1;
				markers = source.parse(objData);
			} catch (NullPointerException ex) {
				Log.e(TAG,
						"=======================Exception running download Runnable."
								+ ex.toString());

				return false;
			}
			// 10.845888,106.600814
		}
		if (markers != null && markers.size() > 0) {
			ARData.addMarkers(markers);
		}
		return true;
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}